<template>
  <div class="profile-container">
    <h2 class="page-title">个人信息</h2>
    
    <!-- 个人信息展示和编辑区域 -->
    <div class="profile-content">
      <!-- 头像部分 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <img :src="userInfo.avatar" alt="用户头像" class="user-avatar">
        </div>
        <h3 class="nickname">{{ userInfo.nickname }}</h3>
        <p class="username">{{ userInfo.username }}</p>
      </div>
      
      <!-- 个人信息表单 -->
      <div class="profile-form">
        <form @submit.prevent="handleUpdate">
          <div class="form-group">
            <label for="nickname">昵称</label>
            <input
              type="text"
              id="nickname"
              v-model="userInfo.nickname"
              placeholder="请输入昵称"
            />
          </div>
          
          <div class="form-group">
            <label for="email">电子邮箱</label>
            <input
              type="email"
              id="email"
              v-model="userInfo.email"
              placeholder="请输入电子邮箱"
            />
          </div>
          
          <div class="form-group">
            <label for="phone">手机号码</label>
            <input
              type="tel"
              id="phone"
              v-model="userInfo.phone"
              placeholder="请输入手机号码"
            />
          </div>
          
          <div class="form-group">
            <label for="gender">性别</label>
            <select id="gender" v-model="userInfo.gender">
              <option value="">请选择</option>
              <option value="male">男</option>
              <option value="female">女</option>
              <option value="other">其他</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="birthDate">出生日期</label>
            <input
              type="date"
              id="birthDate"
              v-model="userInfo.birthDate"
            />
          </div>
          
          <div class="form-group">
            <label for="address">地址</label>
            <textarea
              id="address"
              v-model="userInfo.address"
              placeholder="请输入详细地址"
              rows="3"
            ></textarea>
          </div>
          
          <div v-if="error" class="error-message">{{ error }}</div>
          <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
          
          <div class="form-actions">
            <button type="submit" class="btn-save">保存修改</button>
            <button type="button" class="btn-reset" @click="resetForm">重置</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 账户安全部分 -->
    <div class="account-security">
      <h3>账户安全</h3>
      <button class="btn-change-password" @click="showPasswordModal = true">修改密码</button>
    </div>
    
    <!-- 退出登录按钮 -->
    <div class="logout-section">
      <button class="btn-logout" @click="handleLogout">退出登录</button>
    </div>
  </div>
  
  <!-- 修改密码模态框 -->
  <div v-if="showPasswordModal" class="modal-overlay" @click.self="showPasswordModal = false">
    <div class="modal-content">
      <h3>修改密码</h3>
      <form @submit.prevent="handleChangePassword">
        <div class="form-group">
          <label for="oldPassword">原密码</label>
          <input
            type="password"
            id="oldPassword"
            v-model="passwordForm.oldPassword"
            placeholder="请输入原密码"
            required
          />
        </div>
        
        <div class="form-group">
          <label for="newPassword">新密码</label>
          <input
            type="password"
            id="newPassword"
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码（至少6位）"
            required
          />
        </div>
        
        <div class="form-group">
          <label for="confirmNewPassword">确认新密码</label>
          <input
            type="password"
            id="confirmNewPassword"
            v-model="passwordForm.confirmNewPassword"
            placeholder="请再次输入新密码"
            required
          />
        </div>
        
        <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
        
        <div class="form-actions">
          <button type="submit" class="btn-save">确认修改</button>
          <button type="button" class="btn-cancel" @click="showPasswordModal = false">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getCurrentUser, getUserInfo, updateUserInfo, changePassword, logout } from '../services/auth';

const router = useRouter();
const userInfo = ref({});
const originalUserInfo = ref({});
const error = ref('');
const successMessage = ref('');
const showPasswordModal = ref(false);
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});
const passwordError = ref('');

// 初始化获取用户信息
onMounted(async () => {
  try {
    const currentUser = getCurrentUser();
    if (!currentUser) {
      router.push('/login');
      return;
    }
    
    const fullUserInfo = getUserInfo(currentUser.id);
    if (fullUserInfo) {
      userInfo.value = { ...fullUserInfo };
      originalUserInfo.value = { ...fullUserInfo };
    }
  } catch (err) {
    error.value = err.message;
  }
});

// 处理用户信息更新
const handleUpdate = async () => {
  try {
    error.value = '';
    successMessage.value = '';
    
    const currentUser = getCurrentUser();
    if (!currentUser) {
      throw new Error('请先登录');
    }
    
    await updateUserInfo(currentUser.id, userInfo.value);
    successMessage.value = '个人信息更新成功';
    
    // 3秒后清除成功消息
    setTimeout(() => {
      successMessage.value = '';
    }, 3000);
  } catch (err) {
    error.value = err.message;
  }
};

// 重置表单
const resetForm = () => {
  userInfo.value = { ...originalUserInfo.value };
  error.value = '';
  successMessage.value = '';
};

// 处理修改密码
const handleChangePassword = async () => {
  try {
    passwordError.value = '';
    
    // 验证密码是否一致
    if (passwordForm.value.newPassword !== passwordForm.value.confirmNewPassword) {
      throw new Error('两次输入的新密码不一致');
    }
    
    const currentUser = getCurrentUser();
    if (!currentUser) {
      throw new Error('请先登录');
    }
    
    await changePassword(currentUser.id, passwordForm.value.oldPassword, passwordForm.value.newPassword);
    
    // 重置表单并关闭模态框
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmNewPassword: ''
    };
    showPasswordModal.value = false;
    successMessage.value = '密码修改成功，请重新登录';
    
    // 5秒后自动登出
    setTimeout(() => {
      handleLogout();
    }, 5000);
  } catch (err) {
    passwordError.value = err.message;
  }
};

// 处理退出登录
const handleLogout = () => {
  logout();
  router.push('/login');
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.profile-content {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    align-items: center;
  }
}

.avatar-section {
  text-align: center;
}

.avatar-wrapper {
  margin-bottom: 15px;
}

.user-avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f0f0;
}

.nickname {
  font-size: 1.2rem;
  margin: 0 0 5px 0;
  color: #333;
}

.username {
  font-size: 0.9rem;
  color: #666;
  margin: 0;
}

.profile-form {
  flex: 1;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #666;
  font-weight: 500;
}

input,
select,
textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #42b983;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.btn-save,
.btn-reset,
.btn-cancel,
.btn-change-password,
.btn-logout {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-save {
  background-color: #42b983;
  color: white;
}

.btn-save:hover {
  background-color: #35495e;
}

.btn-reset,
.btn-cancel {
  background-color: #f0f0f0;
  color: #333;
}

.btn-reset:hover,
.btn-cancel:hover {
  background-color: #e0e0e0;
}

.account-security {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.account-security h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.btn-change-password {
  background-color: #4285f4;
  color: white;
}

.btn-change-password:hover {
  background-color: #3367d6;
}

.logout-section {
  text-align: center;
}

.btn-logout {
  background-color: #ff4d4f;
  color: white;
  padding: 10px 30px;
}

.btn-logout:hover {
  background-color: #cf1322;
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 15px;
  font-size: 0.875rem;
}

.success-message {
  color: #52c41a;
  margin-bottom: 15px;
  font-size: 0.875rem;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.modal-content h3 {
  margin: 0 0 20px 0;
  color: #333;
}
</style>